// import 'package:provider/provider.dart';
import 'package:rongcloud_im_wrapper_plugin/rongcloud_im_wrapper_plugin.dart';
import 'package:flutter_application_cyber/model/cn_user_default_cache.dart';
import 'package:flutter_application_cyber/net/cn_net_api.dart';
import 'package:flutter_application_cyber/net/cn_net_helper.dart';
import 'package:flutter_application_cyber/model/cn_net_response.dart';
// import '../pages/im/util/event_bus.dart';

class CnGlobal {
  static const kRongCloudAppKey = "rongCloudAppKey"; //融云appkey

  static late RCIMIWEngine engine;

//初始化全局信息，会在APP启动时执行
  static Future init() async {
    String appKey =
        await CnUserDefaultCacheHelper.getUserDefault(kRongCloudAppKey);
    RCIMIWEngineOptions options = RCIMIWEngineOptions.create();
    RCIMIWEngine newEngine = await RCIMIWEngine.create(appKey, options);
    engine = newEngine;

    CnUserDefaultCacheHelper.getUserDefault(kRongCloudAppKey)
        .then((value) => {initRongCloudAppKeyWithAppKey(value)});
  }

  static initRongCloudAppKeyWithAppKey(String appKey) {
    CnUserDefaultCacheHelper.getUserDefault(kRongCloudAppKey)
        .then((value) async {
      if (value.isNotEmpty) {
        //获取融云token
        CnNetHelper.get(CnApiNet.kPath_getRongCloudToken, params: {})
            .then((value) {
          if (value != null) {
            HDHResponseData response = value;
            if (response.code == 0) {
              RCIMIWConnectCallback? callback = RCIMIWConnectCallback(
                  onDatabaseOpened: (int? code) {},
                  onConnected: (int? code, String? userId) {
                    //  EventBus.instance!.commit(EventKeys.RongIMClientConnected, Null);
//...
                  });

              engine.connect(response.data, 30, callback: callback);
            }
          }
        });
      }
    });
  }
}
